package com.linlei.bluetoothchat;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnItemClick;

/**
 * Created by LinLei on 2015/3/18.
 */
public class DeviceListActivity extends Activity {

    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    @InjectView(R.id.title_paired_devices)
    TextView titlePairedDevices;
    @InjectView(R.id.paired_devices)
    ListView pairedListView;
    @InjectView(R.id.title_new_devices)
    TextView titleNewDevices;
    @InjectView(R.id.new_devices)
    ListView newDevicesListView;
    @InjectView(R.id.button_scan)
    Button buttonScan;

    // 获取默认的蓝牙适配器
    private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;


    // Intent request codes 连接管理都将由REQUEST_CONNECT_DEVICE来实现
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;         //安全
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    Context mContext;

    @InjectView(R.id.toolbar)
    Toolbar mToolbar;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_devices);
        ButterKnife.inject(this);
        mToolbar.setTitle(getString(R.string.activity_device_list));
        //判断蓝牙是否打开,若没有打开，则通过Intent发送REQUEST_ENABLE_BT消息给onActivityResult()函数，
        // 执行打开蓝牙的操作(Intent消息是安卓中不同窗体进行通信的桥梁)
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        init();

    }

    /**
     * 初始化列表，添加监听等
     */
    private void init() {
        //以前配对过的
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
        //新查找出来的
        mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

        pairedListView.setAdapter(mPairedDevicesArrayAdapter);

        newDevicesListView.setAdapter(mNewDevicesArrayAdapter);

        // 添加发现设备的监听
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        // 添加搜索完毕的监听
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);


        // 得到当前已经配对过的设备
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

        // 判断是否有已配对的设备，有则输出所有设备
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
            mPairedDevicesArrayAdapter.notifyDataSetChanged();
        } else {
            String noDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(noDevices);
        }
    }

    @OnClick(R.id.button_scan)
    public void clickScan() {
        //点击开始扫描周围蓝牙设备
        doDiscovery();
    }

    @OnItemClick(R.id.paired_devices)
    public void doConnectPairedDevice(View view, int position) {
        //列表为0，返回
        if (mPairedDevicesArrayAdapter.getCount() == 0)
            return;
        toChat((TextView)view);
    }

    @OnItemClick(R.id.new_devices)
    public void doConnectNewDevice(View view, int position) {
        if(mNewDevicesArrayAdapter.getCount() == 0)
            return;
        toChat((TextView)view);
    }

    /**
     * 得到textview的mac地址
     * @param tv
     * @return
     */
    public void toChat(TextView tv){
        Intent intent = new Intent(DeviceListActivity.this,ChatActivity.class);
        this.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();

        //判断蓝牙是否打开,若没有打开，则通过Intent发送REQUEST_ENABLE_BT消息给onActivityResult()函数，
        // 执行打开蓝牙的操作(Intent消息是安卓中不同窗体进行通信的桥梁)
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // 调用service的stop方法
        if (mBluetoothAdapter != null) {
            mBluetoothAdapter.cancelDiscovery();  //停止搜索
        }
        //注销监听
        this.unregisterReceiver(mReceiver);
    }

    /**
     * 搜索新的设备
     */
    private void doDiscovery() {

        titleNewDevices.setVisibility(View.VISIBLE);

        // 如果处于发现设备的状态下 则不搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }

        mBluetoothAdapter.startDiscovery();
    }


    /**
     * 发现新设备时广播的监听
     */
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // 当发现一个设备时
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 从Intent里得到蓝牙设备对象
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 发现状态不为绑定，添加到newDevice列表中、
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());

                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                if (mNewDevicesArrayAdapter.getCount() == 0) {
                    String noDevices = getResources().getText(R.string.none_found).toString();
                    mNewDevicesArrayAdapter.add(noDevices);
                }
            }
        }
    };


}
